<template>
  <div class="system-monitoring-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>系统监控管理</h1>
      <p class="subtitle">系统状态监控、性能分析、日志管理</p>
    </div>

    <!-- 实时状态概览 -->
    <AppleCard title="系统状态概览" class="status-overview">
      <div class="status-grid">
        <!-- 服务器状态 -->
        <div class="status-card server">
          <div class="status-header">
            <h3>服务器状态</h3>
            <span class="status-indicator" :class="systemStatus.server?.status">
              {{ getStatusText(systemStatus.server?.status) }}
            </span>
          </div>
          <div class="status-metrics">
            <div class="metric">
              <span class="label">运行时间</span>
              <span class="value">{{ formatUptime(systemStatus.server?.uptime) }}</span>
            </div>
            <div class="metric">
              <span class="label">CPU使用率</span>
              <span class="value" :class="getCpuStatusClass(systemStatus.server?.cpu_usage)">
                {{ systemStatus.server?.cpu_usage?.toFixed(1) }}%
              </span>
            </div>
            <div class="metric">
              <span class="label">内存使用率</span>
              <span class="value" :class="getMemoryStatusClass(systemStatus.server?.memory_usage)">
                {{ systemStatus.server?.memory_usage?.toFixed(1) }}%
              </span>
            </div>
            <div class="metric">
              <span class="label">磁盘使用率</span>
              <span class="value" :class="getDiskStatusClass(systemStatus.server?.disk_usage)">
                {{ systemStatus.server?.disk_usage?.toFixed(1) }}%
              </span>
            </div>
          </div>
        </div>

        <!-- 数据库状态 -->
        <div class="status-card database">
          <div class="status-header">
            <h3>数据库状态</h3>
            <span class="status-indicator" :class="systemStatus.database?.status">
              {{ getStatusText(systemStatus.database?.status) }}
            </span>
          </div>
          <div class="status-metrics">
            <div class="metric">
              <span class="label">连接数</span>
              <span class="value">{{ systemStatus.database?.connection_count || 0 }}</span>
            </div>
            <div class="metric">
              <span class="label">平均查询时间</span>
              <span class="value">{{ systemStatus.database?.query_time_avg?.toFixed(2) }}ms</span>
            </div>
          </div>
        </div>

        <!-- 应用状态 -->
        <div class="status-card application">
          <div class="status-header">
            <h3>应用状态</h3>
            <span class="status-indicator" :class="systemStatus.application?.status">
              {{ getStatusText(systemStatus.application?.status) }}
            </span>
          </div>
          <div class="status-metrics">
            <div class="metric">
              <span class="label">在线用户</span>
              <span class="value">{{ systemStatus.application?.active_users || 0 }}</span>
            </div>
            <div class="metric">
              <span class="label">请求总数</span>
              <span class="value">{{ systemStatus.application?.request_count || 0 }}</span>
            </div>
          </div>
        </div>

        <!-- 实时数据 -->
        <div class="status-card realtime">
          <div class="status-header">
            <h3>实时数据</h3>
            <AppleButton 
              type="text" 
              size="small" 
              @click="loadRealtimeData"
              :loading="realtimeLoading"
            >
              刷新
            </AppleButton>
          </div>
          <div class="status-metrics">
            <div class="metric">
              <span class="label">系统负载</span>
              <span class="value">{{ realtimeData.system_load?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="metric">
              <span class="label">活跃连接</span>
              <span class="value">{{ realtimeData.active_connections || 0 }}</span>
            </div>
            <div class="metric">
              <span class="label">请求频率</span>
              <span class="value">{{ realtimeData.request_rate || 0 }}/min</span>
            </div>
            <div class="metric">
              <span class="label">错误率</span>
              <span class="value" :class="getErrorRateClass(realtimeData.error_rate)">
                {{ realtimeData.error_rate?.toFixed(2) || '0.00' }}%
              </span>
            </div>
          </div>
        </div>
      </div>
    </AppleCard>

    <!-- 性能监控图表 -->
    <AppleCard title="性能监控" class="performance-monitoring">
      <div class="chart-controls">
        <AppleSelect
          v-model="performanceTimeRange"
          :options="timeRangeOptions"
          placeholder="时间范围"
          class="time-range-select"
          @change="loadPerformanceMetrics"
        />
        <AppleButton
          type="outline"
          @click="loadPerformanceMetrics"
          :loading="performanceLoading"
        >
          刷新数据
        </AppleButton>
      </div>
      
      <div class="charts-container">
        <div class="chart-item">
          <h4>CPU使用率趋势</h4>
          <div class="chart-placeholder">
            <canvas ref="cpuChart" width="400" height="200"></canvas>
          </div>
        </div>
        <div class="chart-item">
          <h4>内存使用率趋势</h4>
          <div class="chart-placeholder">
            <canvas ref="memoryChart" width="400" height="200"></canvas>
          </div>
        </div>
        <div class="chart-item">
          <h4>响应时间趋势</h4>
          <div class="chart-placeholder">
            <canvas ref="responseTimeChart" width="400" height="200"></canvas>
          </div>
        </div>
        <div class="chart-item">
          <h4>磁盘使用率趋势</h4>
          <div class="chart-placeholder">
            <canvas ref="diskChart" width="400" height="200"></canvas>
          </div>
        </div>
      </div>
    </AppleCard>

    <!-- 日志管理 -->
    <AppleCard title="日志管理" class="log-management">
      <div class="log-controls">
        <div class="filter-controls">
          <AppleSelect
            v-model="logFilters.log_type"
            :options="logTypeOptions"
            placeholder="日志类型"
            class="filter-select"
            clearable
          />
          <AppleSelect
            v-model="logFilters.level"
            :options="logLevelOptions"
            placeholder="日志级别"
            class="filter-select"
            clearable
          />
          <AppleInput
            v-model="logFilters.keyword"
            placeholder="关键词搜索"
            class="keyword-input"
            clearable
          />
          <AppleInput
            v-model="logFilters.ip_address"
            placeholder="IP地址"
            class="ip-input"
            clearable
          />
        </div>
        <div class="action-controls">
          <AppleButton
            type="primary"
            @click="searchLogs"
            :loading="logLoading"
          >
            查询日志
          </AppleButton>
          <AppleButton
            type="outline"
            @click="showLogAnalysis = true"
          >
            日志分析
          </AppleButton>
          <AppleButton
            type="outline"
            @click="showLogExport = true"
          >
            导出日志
          </AppleButton>
        </div>
      </div>

      <AppleTable
        :columns="logColumns"
        :data="logList"
        :loading="logLoading"
        class="log-table"
      >
        <template #level="{ record }">
          <span :class="getLogLevelClass(record.level)">
            {{ record.level }}
          </span>
        </template>
        <template #type="{ record }">
          <span :class="getLogTypeClass(record.type)">
            {{ record.type }}
          </span>
        </template>
      </AppleTable>

      <ApplePagination
        v-model:current="logCurrentPage"
        v-model:size="logPageSize"
        :total="logTotal"
        @change="searchLogs"
        class="log-pagination"
      />
    </AppleCard>

    <!-- 日志统计 -->
    <AppleCard title="日志统计" class="log-statistics">
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-number">{{ logStatistics.total_logs || 0 }}</div>
          <div class="stat-label">总日志数</div>
        </div>
        <div class="stat-card" v-for="(count, type) in logStatistics.type_distribution" :key="type">
          <div class="stat-number">{{ count }}</div>
          <div class="stat-label">{{ getLogTypeLabel(type) }}</div>
        </div>
      </div>

      <div class="stats-charts">
        <div class="chart-section">
          <h4>活跃用户 Top 10</h4>
          <div class="user-list">
            <div 
              class="user-item" 
              v-for="user in logStatistics.top_active_users?.slice(0, 10)" 
              :key="user.user_id"
            >
              <span class="username">{{ user.username }}</span>
              <span class="activity-count">{{ user.activity_count }}</span>
            </div>
          </div>
        </div>
        <div class="chart-section">
          <h4>24小时活动分布</h4>
          <div class="hourly-chart">
            <canvas ref="hourlyChart" width="400" height="200"></canvas>
          </div>
        </div>
      </div>
    </AppleCard>

    <!-- 日志分析弹窗 -->
    <AppleModal
      v-model:visible="showLogAnalysis"
      title="日志分析"
      width="800px"
      class="log-analysis-modal"
    >
      <div class="analysis-form">
        <div class="form-row">
          <label>分析类型：</label>
          <AppleSelect
            v-model="analysisConfig.analysis_type"
            :options="analysisTypeOptions"
            placeholder="选择分析类型"
          />
        </div>
        <div class="form-row">
          <label>时间范围：</label>
          <AppleSelect
            v-model="analysisConfig.time_range"
            :options="timeRangeOptions"
            placeholder="选择时间范围"
          />
        </div>
        <div class="form-row">
          <label>分组方式：</label>
          <AppleSelect
            v-model="analysisConfig.group_by"
            :options="groupByOptions"
            placeholder="选择分组方式"
          />
        </div>
      </div>
      
      <div v-if="analysisResult" class="analysis-result">
        <h4>分析结果</h4>
        <div class="result-content">
          <pre>{{ JSON.stringify(analysisResult, null, 2) }}</pre>
        </div>
      </div>
      
      <template #footer>
        <AppleButton @click="showLogAnalysis = false">取消</AppleButton>
        <AppleButton
          type="primary"
          :loading="analysisLoading"
          @click="executeLogAnalysis"
        >
          开始分析
        </AppleButton>
      </template>
    </AppleModal>

    <!-- 日志导出弹窗 -->
    <AppleModal
      v-model:visible="showLogExport"
      title="导出日志"
      width="600px"
      class="log-export-modal"
    >
      <div class="export-form">
        <div class="form-row">
          <label>导出格式：</label>
          <AppleSelect
            v-model="exportConfig.export_format"
            :options="exportFormatOptions"
            placeholder="选择导出格式"
          />
        </div>
        <div class="form-row">
          <label>日志类型：</label>
          <AppleSelect
            v-model="exportConfig.log_type"
            :options="logTypeOptions"
            placeholder="选择日志类型"
            clearable
          />
        </div>
        <div class="form-row">
          <label>最大记录数：</label>
          <AppleInput
            v-model="exportConfig.max_records"
            type="number"
            placeholder="最大记录数"
          />
        </div>
      </div>
      
      <template #footer>
        <AppleButton @click="showLogExport = false">取消</AppleButton>
        <AppleButton
          type="primary"
          :loading="exportLoading"
          @click="executeLogExport"
        >
          开始导出
        </AppleButton>
      </template>
    </AppleModal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useMessage } from '@/composables/useMessage'
import { monitoringApi } from '@/api/system'
import AppleCard from '@/components/ui/AppleCard.vue'
import AppleButton from '@/components/ui/AppleButton.vue'
import AppleSelect from '@/components/ui/AppleSelect.vue'
import AppleTable from '@/components/ui/AppleTable.vue'
import AppleModal from '@/components/ui/AppleModal.vue'
import ApplePagination from '@/components/ui/ApplePagination.vue'
import AppleInput from '@/components/ui/AppleInput.vue'
import type {
  SystemStatus,
  PerformanceMetrics,
  RealtimeData,
  LogRecord,
  LogStatistics,
  LogQueryParams,
  LogAnalysisRequest,
  LogExportRequest
} from '@/types/system'

// 响应式数据
const systemStatus = reactive<SystemStatus>({
  server: {
    status: 'running',
    uptime: 0,
    cpu_usage: 0,
    memory_usage: 0,
    disk_usage: 0
  },
  database: {
    status: 'connected',
    connection_count: 0,
    query_time_avg: 0
  },
  application: {
    status: 'healthy',
    active_users: 0,
    request_count: 0
  }
})

const realtimeData = reactive<RealtimeData>({
  current_time: '',
  system_load: 0,
  active_connections: 0,
  request_rate: 0,
  error_rate: 0
})

const performanceMetrics = ref<PerformanceMetrics | null>(null)
const logList = ref<LogRecord[]>([])
const logStatistics = reactive<LogStatistics>({
  time_range_hours: 24,
  total_logs: 0,
  type_distribution: {},
  top_active_users: [],
  hourly_distribution: [],
  statistics_generated_at: ''
})

// 加载状态
const realtimeLoading = ref(false)
const performanceLoading = ref(false)
const logLoading = ref(false)
const analysisLoading = ref(false)
const exportLoading = ref(false)

// 弹窗状态
const showLogAnalysis = ref(false)
const showLogExport = ref(false)

// 配置数据
const performanceTimeRange = ref(24)
const logCurrentPage = ref(1)
const logPageSize = ref(50)
const logTotal = ref(0)

const logFilters = reactive<Partial<LogQueryParams>>({
  log_type: '',
  level: '',
  keyword: '',
  ip_address: ''
})

const analysisConfig = reactive<LogAnalysisRequest>({
  analysis_type: 'activity',
  time_range: 24,
  group_by: 'hour'
})

const exportConfig = reactive<LogExportRequest>({
  export_format: 'json',
  log_type: '',
  max_records: 10000
})

const analysisResult = ref<any>(null)

// 配置选项
const timeRangeOptions = [
  { label: '1小时', value: 1 },
  { label: '6小时', value: 6 },
  { label: '12小时', value: 12 },
  { label: '24小时', value: 24 },
  { label: '7天', value: 168 }
]

const logTypeOptions = [
  { label: '系统日志', value: 'system' },
  { label: '操作日志', value: 'operation' },
  { label: '错误日志', value: 'error' },
  { label: '安全日志', value: 'security' },
  { label: '访问日志', value: 'access' }
]

const logLevelOptions = [
  { label: 'DEBUG', value: 'DEBUG' },
  { label: 'INFO', value: 'INFO' },
  { label: 'WARN', value: 'WARN' },
  { label: 'ERROR', value: 'ERROR' }
]

const analysisTypeOptions = [
  { label: '活动分析', value: 'activity' },
  { label: '错误分析', value: 'error' },
  { label: '安全分析', value: 'security' },
  { label: '性能分析', value: 'performance' }
]

const groupByOptions = [
  { label: '按小时', value: 'hour' },
  { label: '按天', value: 'day' },
  { label: '按用户', value: 'user' },
  { label: '按IP', value: 'ip' },
  { label: '按操作', value: 'operation' }
]

const exportFormatOptions = [
  { label: 'JSON格式', value: 'json' },
  { label: 'CSV格式', value: 'csv' }
]

// 表格列配置
const logColumns = [
  { title: '时间', dataIndex: 'timestamp', key: 'timestamp', width: '150px' },
  { title: '类型', dataIndex: 'type', key: 'type', slot: 'type', width: '80px' },
  { title: '级别', dataIndex: 'level', key: 'level', slot: 'level', width: '80px' },
  { title: '操作', dataIndex: 'operation', key: 'operation', width: '120px' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '用户', dataIndex: 'username', key: 'username', width: '100px' },
  { title: 'IP地址', dataIndex: 'client_ip', key: 'client_ip', width: '120px' }
]

// Canvas 引用
const cpuChart = ref<HTMLCanvasElement>()
const memoryChart = ref<HTMLCanvasElement>()
const responseTimeChart = ref<HTMLCanvasElement>()
const diskChart = ref<HTMLCanvasElement>()
const hourlyChart = ref<HTMLCanvasElement>()

const { showMessage } = useMessage()

// 自动刷新定时器
let refreshTimer: NodeJS.Timeout | null = null

// 方法
const loadSystemStatus = async () => {
  try {
    const response = await monitoringApi.getSystemStatus()
    if (response.success) {
      Object.assign(systemStatus, response.data)
    }
  } catch (error) {
    console.error('加载系统状态失败:', error)
  }
}

const loadRealtimeData = async () => {
  realtimeLoading.value = true
  try {
    const response = await monitoringApi.getRealtimeData()
    if (response.success) {
      Object.assign(realtimeData, response.data)
    }
  } catch (error) {
    console.error('加载实时数据失败:', error)
  } finally {
    realtimeLoading.value = false
  }
}

const loadPerformanceMetrics = async () => {
  performanceLoading.value = true
  try {
    const response = await monitoringApi.getPerformanceMetrics(performanceTimeRange.value)
    if (response.success) {
      performanceMetrics.value = response.data
      // 绘制图表
      drawCharts()
    }
  } catch (error) {
    console.error('加载性能指标失败:', error)
  } finally {
    performanceLoading.value = false
  }
}

const searchLogs = async () => {
  logLoading.value = true
  try {
    const params: LogQueryParams = {
      ...logFilters,
      page: logCurrentPage.value,
      size: logPageSize.value
    }
    
    const response = await monitoringApi.queryLogs(params)
    if (response.success) {
      logList.value = response.data.items
      logTotal.value = response.data.total
    }
  } catch (error) {
    console.error('查询日志失败:', error)
    showMessage.error('查询日志失败')
  } finally {
    logLoading.value = false
  }
}

const loadLogStatistics = async () => {
  try {
    const response = await monitoringApi.getLogStatistics(24)
    if (response.success) {
      Object.assign(logStatistics, response.data)
      // 绘制小时分布图表
      drawHourlyChart()
    }
  } catch (error) {
    console.error('加载日志统计失败:', error)
  }
}

const executeLogAnalysis = async () => {
  analysisLoading.value = true
  try {
    const response = await monitoringApi.analyzeLogs(analysisConfig)
    if (response.success) {
      analysisResult.value = response.data
      showMessage.success('日志分析完成')
    }
  } catch (error) {
    showMessage.error('日志分析失败')
    console.error('日志分析失败:', error)
  } finally {
    analysisLoading.value = false
  }
}

const executeLogExport = async () => {
  exportLoading.value = true
  try {
    const response = await monitoringApi.exportLogs(exportConfig)
    if (response.success) {
      showMessage.success('日志导出成功')
      showLogExport.value = false
    }
  } catch (error) {
    showMessage.error('日志导出失败')
    console.error('日志导出失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 绘制图表（简化实现）
const drawCharts = () => {
  if (!performanceMetrics.value) return
  
  // 这里应该使用图表库如Chart.js来绘制图表
  // 为了简化，这里只是模拟
  const drawSimpleChart = (canvas: HTMLCanvasElement | undefined, data: any[], label: string) => {
    if (!canvas) return
    
    const ctx = canvas.getContext('2d')
    if (!ctx) return
    
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.fillStyle = '#007AFF'
    ctx.fillText(`${label} 图表 (${data.length} 个数据点)`, 10, 20)
  }
  
  drawSimpleChart(cpuChart.value, performanceMetrics.value.cpu_usage, 'CPU使用率')
  drawSimpleChart(memoryChart.value, performanceMetrics.value.memory_usage, '内存使用率')
  drawSimpleChart(responseTimeChart.value, performanceMetrics.value.response_time, '响应时间')
  drawSimpleChart(diskChart.value, performanceMetrics.value.disk_usage, '磁盘使用率')
}

const drawHourlyChart = () => {
  if (!hourlyChart.value) return
  
  const ctx = hourlyChart.value.getContext('2d')
  if (!ctx) return
  
  ctx.clearRect(0, 0, hourlyChart.value.width, hourlyChart.value.height)
  ctx.fillStyle = '#007AFF'
  ctx.fillText(`24小时活动分布 (${logStatistics.hourly_distribution.length} 个小时)`, 10, 20)
}

// 工具方法
const formatUptime = (seconds: number): string => {
  if (!seconds) return '0天'
  
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (days > 0) return `${days}天${hours}小时`
  if (hours > 0) return `${hours}小时${minutes}分钟`
  return `${minutes}分钟`
}

const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    running: '运行中',
    stopped: '已停止',
    error: '错误',
    connected: '已连接',
    disconnected: '断开连接',
    healthy: '健康',
    warning: '警告'
  }
  return statusMap[status] || status
}

const getCpuStatusClass = (usage: number): string => {
  if (usage < 50) return 'status-good'
  if (usage < 80) return 'status-warning'
  return 'status-danger'
}

const getMemoryStatusClass = (usage: number): string => {
  if (usage < 70) return 'status-good'
  if (usage < 90) return 'status-warning'
  return 'status-danger'
}

const getDiskStatusClass = (usage: number): string => {
  if (usage < 80) return 'status-good'
  if (usage < 95) return 'status-warning'
  return 'status-danger'
}

const getErrorRateClass = (rate: number): string => {
  if (rate < 1) return 'status-good'
  if (rate < 5) return 'status-warning'
  return 'status-danger'
}

const getLogLevelClass = (level: string): string => {
  return {
    'log-debug': level === 'DEBUG',
    'log-info': level === 'INFO',
    'log-warn': level === 'WARN',
    'log-error': level === 'ERROR'
  }
}

const getLogTypeClass = (type: string): string => {
  return {
    'type-system': type === 'system',
    'type-operation': type === 'operation',
    'type-error': type === 'error',
    'type-security': type === 'security',
    'type-access': type === 'access'
  }
}

const getLogTypeLabel = (type: string): string => {
  const typeMap: Record<string, string> = {
    system: '系统',
    operation: '操作',
    error: '错误',
    security: '安全',
    access: '访问'
  }
  return typeMap[type] || type
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadSystemStatus(),
    loadRealtimeData(),
    loadPerformanceMetrics(),
    searchLogs(),
    loadLogStatistics()
  ])
  
  // 设置自动刷新
  refreshTimer = setInterval(() => {
    loadRealtimeData()
  }, 30000) // 每30秒刷新一次实时数据
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped lang="scss">
.system-monitoring-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 24px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 28px;
      font-weight: 600;
      color: #1d1d1f;
    }
    
    .subtitle {
      margin: 0;
      color: #6e6e73;
      font-size: 16px;
    }
  }
  
  // 状态概览样式
  .status-overview {
    margin-bottom: 24px;
    
    .status-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 20px;
      
      .status-card {
        padding: 20px;
        background: #f2f2f7;
        border-radius: 12px;
        
        .status-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #1d1d1f;
          }
          
          .status-indicator {
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
            
            &.running, &.connected, &.healthy {
              background: #d1f2eb;
              color: #00875a;
            }
            
            &.stopped, &.disconnected, &.error {
              background: #ffecee;
              color: #de350b;
            }
            
            &.warning {
              background: #fff4e6;
              color: #ff8b00;
            }
          }
        }
        
        .status-metrics {
          .metric {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #e1e1e6;
            
            &:last-child {
              border-bottom: none;
            }
            
            .label {
              color: #6e6e73;
              font-size: 14px;
            }
            
            .value {
              font-weight: 600;
              font-size: 14px;
              color: #1d1d1f;
              
              &.status-good { color: #30d158; }
              &.status-warning { color: #ff9f0a; }
              &.status-danger { color: #ff3b30; }
            }
          }
        }
      }
    }
  }
  
  // 性能监控样式
  .performance-monitoring {
    margin-bottom: 24px;
    
    .chart-controls {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;
      align-items: center;
      
      .time-range-select {
        width: 150px;
      }
    }
    
    .charts-container {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 20px;
      
      .chart-item {
        h4 {
          margin: 0 0 12px 0;
          font-size: 14px;
          font-weight: 600;
          color: #1d1d1f;
        }
        
        .chart-placeholder {
          background: #f9f9f9;
          border-radius: 8px;
          padding: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          min-height: 200px;
          
          canvas {
            max-width: 100%;
            height: auto;
          }
        }
      }
    }
  }
  
  // 日志管理样式
  .log-management {
    margin-bottom: 24px;
    
    .log-controls {
      margin-bottom: 20px;
      
      .filter-controls {
        display: flex;
        gap: 12px;
        margin-bottom: 12px;
        flex-wrap: wrap;
        
        .filter-select, .keyword-input, .ip-input {
          min-width: 150px;
        }
      }
      
      .action-controls {
        display: flex;
        gap: 12px;
      }
    }
    
    .log-table {
      margin-bottom: 16px;
    }
  }
  
  // 日志统计样式
  .log-statistics {
    .stats-overview {
      display: flex;
      gap: 16px;
      margin-bottom: 24px;
      flex-wrap: wrap;
      
      .stat-card {
        flex: 1;
        min-width: 120px;
        text-align: center;
        padding: 16px;
        background: #f2f2f7;
        border-radius: 12px;
        
        .stat-number {
          font-size: 24px;
          font-weight: 600;
          color: #007aff;
          margin-bottom: 4px;
        }
        
        .stat-label {
          font-size: 12px;
          color: #6e6e73;
        }
      }
    }
    
    .stats-charts {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;
      
      .chart-section {
        h4 {
          margin: 0 0 16px 0;
          font-size: 16px;
          font-weight: 600;
          color: #1d1d1f;
        }
        
        .user-list {
          .user-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: #f9f9f9;
            border-radius: 8px;
            margin-bottom: 8px;
            
            .username {
              font-weight: 500;
              color: #1d1d1f;
            }
            
            .activity-count {
              font-weight: 600;
              color: #007aff;
            }
          }
        }
        
        .hourly-chart {
          background: #f9f9f9;
          border-radius: 8px;
          padding: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          min-height: 200px;
        }
      }
    }
  }
  
  // 日志级别样式
  .log-debug { color: #6e6e73; }
  .log-info { color: #007aff; }
  .log-warn { color: #ff9f0a; }
  .log-error { color: #ff3b30; }
  
  // 日志类型样式
  .type-system { color: #007aff; }
  .type-operation { color: #30d158; }
  .type-error { color: #ff3b30; }
  .type-security { color: #ff9f0a; }
  .type-access { color: #6e6e73; }
  
  // 弹窗样式
  .analysis-form, .export-form {
    .form-row {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      
      label {
        width: 100px;
        font-weight: 500;
        color: #1d1d1f;
      }
      
      .apple-select, .apple-input {
        flex: 1;
      }
    }
  }
  
  .analysis-result {
    margin-top: 20px;
    
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      font-weight: 600;
      color: #1d1d1f;
    }
    
    .result-content {
      background: #f9f9f9;
      border-radius: 8px;
      padding: 16px;
      max-height: 400px;
      overflow-y: auto;
      
      pre {
        margin: 0;
        font-size: 12px;
        line-height: 1.5;
        color: #1d1d1f;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .system-monitoring-container {
    padding: 16px;
    
    .status-grid {
      grid-template-columns: 1fr;
    }
    
    .charts-container {
      grid-template-columns: 1fr;
    }
    
    .stats-charts {
      grid-template-columns: 1fr;
    }
    
    .filter-controls {
      flex-direction: column;
      
      .filter-select, .keyword-input, .ip-input {
        min-width: unset;
        width: 100%;
      }
    }
    
    .action-controls {
      flex-direction: column;
    }
  }
}
</style>